# -*- coding:utf-8 -*-

# @Time : 2023/4/21 8:41
# @Author : 快乐的小猴子
# @Version : 
# @Function : 

import requests
import os
from conf import setting


class HangXianInfos:

    def get_desk_dir(self, key):
        """
        校验桌面存储文件的路径是否存在，若不存在则创建
        :param key:
        :return:
        """
        # 判断是否为 百元机票专场 的key，校验路径，如果不是则校验国内一口价机票、国际及地区机票路径
        if key == list(setting.inter_datas[2].keys())[0]:
            desk_dir = os.path.join(os.path.expanduser("~"), setting.base_infos_list[0]) + setting.base_infos_list[
                1].format(key)
            if not os.path.exists(desk_dir):
                os.makedirs(desk_dir)
        else:
            desk_dir = os.path.join(os.path.expanduser("~"), setting.base_infos_list[0]) + setting.base_infos_list[
                2].format(key)
            if not os.path.exists(desk_dir):
                os.makedirs(desk_dir)
        return desk_dir

    def send(self):
        """
        发送请求信息，获取服务器返回的页面数据
        :return:
        """
        print(setting.base_infos_list[16])
        resp = requests.post(setting.url, data=setting.data, headers=setting.headers, proxies=setting.proxies).json()
        # resp = requests.post(setting.url, data=setting.data, headers=setting.headers).json()
        return resp

    def get_datas(self, resp):
        """
        初步筛选处理服务器返回的也页面数据，返回数据字典
        :param resp:
        :return:
        """
        all_datas_dics = {}
        # 国内各大地区百元机票专场部分
        flights_datas = resp['flights']
        # 国际及地区机票部分
        data_international_weeks = resp['data']['international']['weeks']
        data_international_all = resp['data']['international']['all']
        data_international_areatime = resp['data']['international']['areatime']
        # 国内各大地区原价部分
        data_internal_weeks = resp['data']['internal']['weeks']
        data_internal_all = resp['data']['internal']['all']
        data_internal_areatime = resp['data']['internal']['areatime']
        # 将筛选处理后的数据添加到字段 all_datas_dics中
        all_datas_dics['flights_datas'] = flights_datas
        all_datas_dics['data_international_weeks'] = data_international_weeks
        all_datas_dics['data_international_all'] = data_international_all
        all_datas_dics['data_international_areatime'] = data_international_areatime
        all_datas_dics['data_internal_weeks'] = data_internal_weeks
        all_datas_dics['data_internal_all'] = data_internal_all
        all_datas_dics['data_internal_areatime'] = data_internal_areatime
        return all_datas_dics

    def get_inter_datas(self, key, datas):
        """
        筛选国内各大地区一口价机票和国际及地区机票部分
        :param key:
        :param datas:
        :return:
        """
        num = 1
        while num <= 4:
            week = datas[str(num)]['week']
            name = datas[str(num)]['name']
            time = datas[str(num)]['time']
            flights = datas[str(num)]['flights']
            print(setting.base_infos_list[3] + setting.base_infos_list[4].format(week, name, time) + '\n' +
                  setting.base_infos_list[5])
            # 校验文件路径
            desk_dir = self.get_desk_dir(key)
            # 处理文件名格式
            file_name = name.replace('/', "")
            # 将数据存储到文件中
            with open(setting.base_infos_list[6].format(desk_dir, file_name), 'w', encoding='utf-8') as fp:
                fp.write(setting.base_infos_list[7])
                for i in range(0, len(flights)):
                    print(flights[i])
                    hangxian = flights[i]['from'] + '——' + flights[i]['to']
                    hangxian_cde = flights[i]['fromCode'] + '——' + flights[i]['toCode']
                    price = '￥' + flights[i]['price']
                    date = flights[i]['date']
                    fp.write(hangxian + '|' + hangxian_cde + '|' + price + '|' + date + '\n')
                    print(i + 1, hangxian, hangxian_cde, price, date)
                    print(setting.base_infos_list[8].format(num, name, i + 1))
            num += 1

    def get_flights_datas(self, key, datas):
        """
        筛选处理国内各大地区百元机票专场部分
        :param key:
        :param datas:
        :return:
        """
        print(setting.base_infos_list[9] + setting.base_infos_list[10])
        # 校验文件路径是否存在
        desk_dir = self.get_desk_dir(key)
        # 将数据存储在csv文件中
        with open(setting.base_infos_list[11].format(desk_dir), 'w', encoding='utf-8') as fs:
            fs.write(setting.base_infos_list[12])
            for i in range(0, len(datas)):
                hangxian = datas[i]['from'] + '——' + datas[i]['to']
                hangxian_cde = datas[i]['fromCode'] + '——' + datas[i]['toCode']
                area = datas[i]['area']
                price = '￥' + datas[i]['price']
                oldprice = '￥' + datas[i]['oldprice']
                actDate = datas[i]['sDate'] + ' — ' + datas[i]['eDate']
                showTime = datas[i]['showStart'] + ' — ' + datas[i]['showEnd']
                fs.write(
                    hangxian + '|' + hangxian_cde + '|' + area + '|' + price + '|' + oldprice + '|' + actDate + '|' + showTime + '\n')
                print(i + 1, hangxian, hangxian_cde, area, price, oldprice, actDate, showTime)
                print(setting.base_infos_list[13].format(i + 1))

    def get_all_datas(self, key, datas):
        """
        获取所有的一口价机票数据，并存储到文件中
        :param key:
        :param datas:
        :return:
        """
        print(setting.base_infos_list[14].format(key))
        # 校验文件路径是否存在
        desk_dir = self.get_desk_dir(key)
        # 将数据存储到文件中
        with open(setting.base_infos_list[15].format(desk_dir, key), 'w', encoding='utf-8') as fg:
            fg.write(setting.base_infos_list[17])
            for i in range(0, len(datas)):
                hangxian = datas[i]['from'] + '——' + datas[i]['to']
                hangxian_cde = datas[i]['fromCode'] + '——' + datas[i]['toCode']
                price = '￥' + datas[i]['price']
                area = datas[i]['area']
                eDate = datas[i]['eDate']
                fg.write(hangxian + '|' + hangxian_cde + '|' + price + '|' + area + '|' + eDate + '\n')
                print(i + 1, hangxian, hangxian_cde, price, area, eDate)

    def save_files(self, all_datas_dics):
        """
        保存文件
        :param all_datas_dics:
        :return:
        """
        for i in range(0, len(setting.inter_datas)):
            key = list(setting.inter_datas[i].keys())[0]
            # 如果key值为百元机票专场key，则value为字符串 flights_datas
            if key == list(setting.inter_datas[2].keys())[0]:
                value = list(setting.inter_datas[i].values())[0]
                datas = all_datas_dics[value]
                self.get_flights_datas(key, datas)
            # 否则，value为列表类型，需要遍历出 _week和 _all对应的 value值
            else:
                for j in range(0, len(list(setting.inter_datas[i].values())[0])):
                    value = list(setting.inter_datas[i].values())[0][j]
                    datas = all_datas_dics[value]
                    if value == 'data_internal_all' or value == 'data_international_all':
                        self.get_all_datas(key, datas)
                    else:
                        self.get_inter_datas(key, datas)

    def get_tejia_datas(self):
        resp = self.send()
        all_datas_dics = self.get_datas(resp)
        self.save_files(all_datas_dics)
